<template>
  <div class="member-header">
    <div class="btn-group">
      <!-- 按钮组 -->
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!dept || dept.id <= 0"
          @click="showUserEditor()"
        >新增</el-button>
        <el-button type="primary" icon="el-icon-search" @click="showUserSearch()">搜索</el-button>
      </el-button-group>

      <el-dropdown>
        <el-button type="primary">
          导入
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="importFile()">导入</el-dropdown-item>
          <el-dropdown-item @click.native="importCompleteFile()">完善信息</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-dropdown>
        <el-button type="primary">
          导出
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="downloadUsers()">人员表</el-dropdown-item>
          <el-dropdown-item @click.native="downloadUserAndCert()">人员及证件</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-button-group>
        <el-button type="primary" @click="showUserDict()">信息选项</el-button>
        <el-button type="primary" @click="showCraft()">工种类型</el-button>
      </el-button-group>

      <el-button-group>
        <el-button type="danger" @click="multiDelete()" :disabled="!canMultiDelete">批量删除</el-button>
      </el-button-group>
    </div>
    <batch-import
      v-show="batchImportVisible === false"
      ref="batchImport"
      message="一次最多导入200条数据"
      @uploadFile="uploadFile"
    />

    <batch-import
      v-show="batchImportVisible === false"
      ref="completeImport"
      message="一次最多导入200条数据"
      @uploadFile="uploadComplateFile"
    />

    <member-editor v-if="memberEditorVisible" ref="memberEditor" @refreshDataList="loadUserList" />

    <user-search
      v-if="userSearchVisible"
      ref="userSearch"
      @onClose="onCloseSearch"
      @onSearch="onSearch"
    />

    <user-craft ref="userCraft" v-if="craftVisible" />
    <user-dictionary ref="userDict" v-if="userDictVisible" />
  </div>
</template>

<script>
import MemberEditor from '../member-editor'
import UserSearch from '../user-search'
import BatchImport from '../../questions/batchimport'
import UserCraft from '../user-craft'
import UserDictionary from '../user-dictionary'

export default {
  name: 'memberHeader',
  components: {
    MemberEditor,
    UserSearch,
    BatchImport,
    UserCraft,
    UserDictionary
  },
  props: {
    dept: {
      type: Object,
      required: false,
      default: null
    },
    canMultiDelete: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      batchImportVisible: false,
      memberEditorVisible: false,
      userSearchVisible: false,
      userDictVisible: false,
      craftVisible: false,
      isSearch: false,
      searchCondition: {}
    }
  },
  methods: {
    multiDelete() {
      this.$emit('multiDelete')
    },
    loadUserList() {
      this.$emit('loadUserList')
    },
    // 新增用户
    showUserEditor() {
      this.memberEditorVisible = true
      this.$nextTick(() => {
        this.$refs.memberEditor.init(this.dept)
      })
    },
    // 工种
    showCraft() {
      this.craftVisible = true
      this.$nextTick(() => {
        this.$refs.userCraft.init()
      })
    },
    // 人员字典
    showUserDict() {
      this.userDictVisible = true
      this.$nextTick(() => {
        this.$refs.userDict.init()
      })
    },
    // 搜索
    showUserSearch() {
      this.userSearchVisible = true
    },
    onSearch(searchCondition) {
      this.isSearch = true
      this.searchCondition = searchCondition
      this.$emit('onSearch', searchCondition)
    },
    onCloseSearch() {
      this.isSearch = false
      this.userSearchVisible = false
      this.searchCondition = null
      this.$emit('onCloseSearch')
    },
    // 导入文件
    importFile() {
      // this.batchImportVisible = true
      this.$nextTick(() => {
        this.$refs.batchImport.init(4)
      })
    },
    importCompleteFile() {
      // this.batchImportVisible = true
      this.$nextTick(() => {
        this.$refs.completeImport.init(4)
      })
    },
    // 导入后上传文件处理
    async uploadFile(file) {
      let Loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let data = new FormData()
      data.append('file', file)
      let res = await this.$http.post('/usercenter-admin/import/user', data)
      Loading.close()

      if (res.code === 200) {
        this.$notify.success({ title: '成功', message: '导入成功' })
        this.batchImportVisible = false
        /* 1. 重新加载用户关联信息 */
        this.batchImportVisible = false
        await this.$store.dispatch('user/loadUserDict_4')
        await this.$store.dispatch('user/loadCraftList')
        await this.$store.dispatch('user/loadDeptList')

        /* 2. 重新创建部门树 */
        this.$emit('refreshDeptMenu')

        /* 3. 重新加载用户列表 */
        this.pageIndex = 1
        await this.loadUserList()

        /* 4. 关闭导入窗口 */
        this.batchImportVisible = false
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    },
    async uploadComplateFile(file) {
      let Loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let data = new FormData()
      data.append('file', file)
      let res = await this.$http.post(
        '/usercenter-admin/import/perfectUserInfo',
        data
      )
      Loading.close()

      if (res && res.code === 200) {
        this.batchImportVisible = false
        this.$notify.success({ title: '成功', message: '导入成功' })
        /* 1. 重新加载用户关联信息 */
        await this.$store.dispatch('user/loadUserDict_4')
        await this.$store.dispatch('user/loadCraftList')
        await this.$store.dispatch('user/loadDeptList')

        /* 2. 重新创建部门树 */
        this.$emit('refreshDeptMenu')

        /* 3. 重新加载用户列表 */
        this.pageIndex = 1
        await this.loadUserList()

        /* 4. 关闭导入窗口 */
        this.batchImportVisible = false
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
      }
    },
    async downloadUsers() {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let condition = JSON.parse(JSON.stringify(this.searchCondition))
      delete condition.deptIds
      let request = this.isSearch
        ? condition
        : { deptId: this.dept ? this.dept.id : 0 }
      let res = await this.$http.post(
        '/usercenter-admin/import/exportuserbaseinfo',
        request
      )
      if (res.code === 200) {
        let userList = this.sort(res.data)
        let excel = await import('../export-excel')
        excel.exportUsers(userList)
      } else {
        this.$notify.error({
          title: '失败',
          message: '导出人员列表失败，请重试！'
        })
      }
      loading.close()
    },
    async downloadUserAndCert() {
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      })
      let res = await this.$http.post('/usercenter-admin/import/exportallinfo')
      if (res.code === 200) {
        let dataList = this.sort(res.data, true)
        let excel = await import('../export-excel')
        excel.exportUserAndCert(dataList)
      } else {
        this.$notify.error({
          title: '失败',
          message: '导出人员及证件列表失败，请重试！'
        })
      }
      loading.close()
    },
    // 根据部门排序和人员排序
    sort(userList, withCert = false) {
      let result = []
      this.recursive(result, this.deptTree, userList, withCert)
      return result
    },
    recursive(dest, children, userList, withCert) {
      if (!withCert) {
        children.forEach(child => {
          let users = userList.filter(x => x.deptId === child.id)
          users.sort((a, b) => a.userSort - b.userSort)
          dest.push(...users)

          if (child.children) {
            this.recursive(dest, child.children, userList, false)
          }
        })
      } else {
        children.forEach(child => {
          let users = userList.filter(x => x.userBaseInfo.deptId === child.id)
          users.sort(
            (a, b) => a.userBaseInfo.userSort - b.userBaseInfo.userSort
          )
          dest.push(...users)

          if (child.children) {
            this.recursive(dest, child.children, userList, true)
          }
        })
      }
    }
  },
  computed: {
    deptTree() {
      return this.$store.getters['user/deptTree']
    }
  }
}
</script>

<style>
</style>
